# -*- coding: binary -*-

# GitLab helpers mixin
module Msf::Exploit::Remote::HTTP::Gitlab::Helpers
  # Helper methods are private and should not be called by modules

  private

  # Returns the POST data for a Gitlab login request
  #
  # @param user [String] Username
  # @param pass [String] Password
  # @param csrf_token [String] CSRF token
  # @return [Hash] The post data for vars_post Parameter
  def gitlab_helper_login_post_data(user, pass, csrf_token)
    post_data = {
      'utf8' => '✓',
      'authenticity_token' => csrf_token,
      'user[login]' => user,
      'user[password]' => pass,
      'user[remember_me]' => 0
    }
    post_data
  end

  # Extract the CSRF token at the given URI using the provided regex
  #
  # @param path [String] the URI to retrieve the CSRF token from
  # @param regex [String] the regex used to extract the CSRF token from the HTML response
  # @return [String] the CSRF token
  # @raise [Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError] if the request timed out
  # @raise [Msf::Exploit::Remote::HTTP::Gitlab::Error::CsrfError] if it was not possible to extract the CSRF token
  def gitlab_helper_extract_csrf_token(path:, regex:)
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, path),
      'keep_cookies' => true
    })

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::ClientError.new message: 'Request timed out' if res.nil?

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::CsrfError unless res&.code == 200

    token = res.body[regex, 1]

    raise Msf::Exploit::Remote::HTTP::Gitlab::Error::CsrfError, "Could not successfully extract CSRF token using the regex #{regex}" if token.nil?

    token
  end
end
